package com.korubo.web.contrller;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.korubo.kit.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileContrller {

    @Value("${upload.path}")
    private String uploadPath;
    @Value("${upload.profile}")
    private String profile;

    @RequestMapping("/upload")
    public R upload(MultipartFile file) {
        //上传文件到本地
        try {
            //获取文件后缀
            String type = file.getContentType().split("/")[1];
            String path = profile + "/" + DateUtil.format(DateUtil.date(), "yyyy/MM/dd");

            String imgPath = path +"/" + UUID.randomUUID() + "." + type;
            String s = uploadPath + imgPath;
            log.info("上传路径：{}", s);

            File file1 = new File(s);
            if (!file1.exists()) {
                file1.mkdirs();
            }

            file.transferTo(new File(s));
            return R.ok(imgPath);
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail("上传失败");
        }

    }
}
